<?php
 
// Include the model definition you want to overload if needed
require_once('model/User.php'); 

// Extends from the model class
class User extends DataObjects_User
{	
	// user information
	const APPLICATION_ADMIN			= 1;
	
	//------ Admin information ----
	const NHANVIEN = 0;
	const QUANLY = 1;
	const QUANTRI = 2;
	
	
	/**
	 * create user
	 *
	 */
	function create()
	{
		$this->password = sha1($this->password);
		$this->last_login_date = "0000-00-00 00:00:00";
		$id = $this->insert();
		
		if (!$this->code)
		{
			$this->code = $this->id;
			$this->update();
			
		}
	}
	
	/**
	 * validate user input
	 *
	 * @return bool true if user input is valid, otherwise return false
	 */
	function validateInput()
	{
		if ($this->id)
		{
			return $this->validateCode() && $this->validateEmail() && $this->validateLastName();			
		}
		else 
		{
			return $this->validateEmail() && $this->validatePassword() && $this->validateConfirmPassword() && $this->validateLastName();
		}
	}
	
	/**
	 *	validate code
	 *
	 * @return bool true if email is valid, otherwise return false
	 */
	function validateCode()
	{
		if ($this->code && User::checkCodeExist($this->code, $this->id))
		{
			ErrorHandler::add('_MSG_CODE_EXIST');
			return false;
		}
		return true;
	}
	
	/**
	 *	validate email
	 *
	 * @return bool true if email is valid, otherwise return false
	 */
	function validateEmail()
	{
		if ($this->email == '')
		{
			ErrorHandler::add('_ERR_EMAIL_CANNOT_BE_EMPTY');
			return false;
		}
		if (!Utils::checkEmailValid($this->email))
		{
			ErrorHandler::add('_ERR_INVALID_EMAIL');
			return false;
		}
		
		if (User::checkUserExist($this->email, $this->id))
		{
			ErrorHandler::add('_ERR_EMAIL_EXIST');
			return false;
		}
		return true;
	}
	
	/**
	 * validate password
	 *
	 * @return bool true if password is valid, otherwise return false
	 */
	function validatePassword()
	{
		if (strlen($this->password) <= 0 )
		{
			ErrorHandler::add('_ERR_PASSWORD_CANNOT_BE_EMPTY');
			return false;
		}
		
		if (strlen($this->password) < 6 )
		{
			ErrorHandler::add('_ERR_MIN_LENGTH_PASSWORD_SERVER');
			return false;
		}
		
		if (strlen($this->password) > Parameter::MAX_LENGTH_PASSWORD)
		{
			ErrorHandler::add('_ERR_MAX_LENGTH_PASSWORD_SERVER');
			return false;
		}
		return true;
	}
	
	/**
	 * validate confirm password
	 *
	 * @return bool true if confirm password is valid, otherwise return false
	 */
	function validateConfirmPassword()
	{
		if ($this->password != $this->confirm_password)
		{
			ErrorHandler::add('_ERR_INVALID_CONFIRM_PASSWORD');
			return false;
		}
		return true;
	}
	
	/**
	 * validate last name
	 *
	 * @return bool true if last name is valid, otherwise return false
	 */
	function validateLastName()
	{
		if (strlen($this->last_name) <= 0 )
		{
			ErrorHandler::add('_ERR_LAST_NAME_CANNOT_BE_EMPTY');
			return false;
		}
		
		if (strlen($this->last_name) > Parameter::MAX_LENGTH_NAME )
		{
			ErrorHandler::add('_ERR_MAX_LENGTH_NAME');
			return false;
		}
		return true;
	}
	/**
	 * Delete a user
	 *
	 */
	function deleteUser()
	{
		//update user data
		$this->last_name = $this->id . $this->last_name;
		$this->is_disabled = 1;
		$this->update();
		
		//update contact data
		$contact = new Contact();
		$contact->id_master_user = $this->id;
		$contact->find(true);
		if ($contact->N)
		{
			$user = new User();
			$user->id_contact = $contact->id;
			$user->is_disabled = 0;
			$user->orderBy('id');
			$user->limit(1);
			$user->find(true);
			if ($user->N)
			{
				$contact->id_master_user = $user->id;
				$contact->update();
			}
		}
		
	}
	
	/*
	 * Perform login
	 * @param string $username
	 * @param string $password
	 *
	 * return array $error
	 */ 
	public static function performLogin($username, $password)
	{		
		$errors = NULL;
		
		// free all SESSION variables
		FRM_Session::remove();
			
		//Cfer::setBackLink("login");
		
		$user = new User();		
		$user->connectUser($username, $password);
		
		if (sizeof($errors) == 0)
		{
			if ($user->id <> NULL)
			{	
				FRM_Session::set('user_serialize_admin', serialize($user) );
			}
			else
			{
				if ($user->id <> NULL)
					$errors[] = '_LB_NOT_GRANTED';
				else
					$errors[] = '_LB_INVALID_LOGIN_OR_PASSWORD';			
			}
		}
		
		return $errors;
	}

	// check login and use SHA1 to encode password
	function connectUser($login, $password, $encode_password = true)
	{
		$this->whereAdd("email = '" . $this->escape($login) . "'");		
		$this->whereAdd("password = '" . (($encode_password) ? sha1($this->escape($password)) : $this->escape($password)) . "'");			
		
		$this->is_disabled = 0;
		
		$this->selectAdd();
		$this->selectAdd('user.*');
		
		$this->find();
		
		if ($this->N)
		{
			$this->fetch();		
		}		
	}

	
	/**
	 * Update Date Last Login to current date if user login to the system
	 *
	 * @return data_object updated
	 */
	function updateLogin() {
		$this->last_login_date = date("Y-m-d G:i:s");
		$this->query("update user set last_login_date='$this->last_login_date' where id = $this->id");
		//$this->update();
	}
	

	
	/**
	 * Check if Login is admin
	 *
	 * @return boolean true if Login is support/admin
	 */
	function isController() {
		return isset($this->is_controller) && ($this->is_controller);
	}
	
	/**
	 * Check if Login is a Support
	 *
	 * @return boolean true if Login is a Support
	 */
	function isQuanly() {
		return isset ($this->is_controller) && ($this->is_controller == self::QUANLY );
	}
	
	/**
	 * Check if Login is a Admin
	 *
	 * @return boolean true if Login is a Admin
	 */
	function isNhanvien() {
		return isset ($this->is_controller) && ($this->is_controller == 1);
	}
		
	/**
	 * Check if logging user is allowed to access project
	 *
	 * @return boolean true if user can access project
	 */
	private function isAllowedAccessProject($application_id = 0)
	{
		
		return true;
	}

	/**
	 * Check the user is exist
	 *
	 * @param string $email
	 * @return boolean if the user is exist return true otherwise return false
	 */
	public static function checkUserExist($email, $id)
	{
		$user = new User();		
		$user->email = $email;
		$user->is_disabled = 0;
		
		if ($id)
			$user->whereAdd("id <> $id");
		
		$user->find();
		return $user->N > 0;
	}
	
	/**
	 * Check the code is exist
	 *
	 * @param string $code
	 * @return boolean if the user is exist return true otherwise return false
	 */
	public static function checkCodeExist($code, $id)
	{
		$user = new User();		
		$user->code = $code;
		$user->is_disabled = 0;
		
		if ($id)
			$user->whereAdd("id <> $id");
		
		$user->find();
		return $user->N > 0;
	}
	
	public static function getList($id_branch = 0, $type = -1, $name = '', $is_have_pager = true)
	{
		$user = new User();
		
		$branch = new Branch();
		$user->joinAdd($branch, 'LEFT');
		
		if ($id_branch)
		{
			$user->id_branch = $id_branch;
		}
		
		$user->selectAdd();
		$user->selectAdd('user.is_controller as type, user.id , user.email, user.telephone,
						user.first_name, user.last_name, user.last_login_date, user.code');
		$user->selectAdd("branch.name as branch_name ");
		
		$user->whereAdd("is_disabled = 0 and (first_name like '%" . $user->escape($name,TRUE) . "%' or last_name like '%" . $user->escape($name,TRUE) . "%')");
		
		if ($type != -1)
			$user->is_controller = $type;
		
		$user->orderBy('last_name, first_name');
		
		if ($is_have_pager) 
		{
			$p = new FRM_Pager('page',Parameter::$params["PAGING_DEFAULT_ITEM_PER_PAGE"], new FRM_Pager_RangeIterator(1, Parameter::$params['PAGING_DEFAULT_PAGE_DELTA'], 1));		
			$user->setPager($p);
		}
		
		$user->find();
		
		return $user;
	}
	
	/**
	 * Is current user have permission to change password
	 *
	 * @param Object $current_user
	 * @param Interger $id
	 * @return boolean
	 */
	public function checkChangePassRole($current_user, $id)
	{	
		$user = new User();
		$user->id = $id;
		$user->find();
		$user->fetch();		
		if($user->N == 0)
		{
			ErrorHandler::add('_LB_USER_NOT_EXIST');
			return false;
		} 
		
		if($current_user->is_controller == self::NHANVIEN 
		   || $current_user->is_controller == self::QUANLY)
		{	
			if($current_user->id != $id)
			{  
			   if($current_user->is_controller < $user->is_controller)
			   {    
			   		ErrorHandler::add('_LB_NOT_GRANTED');
			   		return false;
			   }
			}		
		}
		else 
		{
			if($current_user->id != $id)
			{  
			   $change_user = new User();
			   $contact = new Contact();
			   $change_user->selectAdd();
			   $change_user->selectAdd('user.id id, user.id_contact contact_id
										, contact.id_master_user master_id');
			   $change_user->joinAdd($contact, 'LEFT');
			   $change_user->whereAdd('user.id ='. $id);
			   $change_user->find(); 	
			   $change_user->fetch();	
			   if($change_user->contact_id == $current_user->contact_id
			      && $change_user->master_id == $current_user->id)
			   {	
			   		return true;
			   }
			   else 
			   {
			   		ErrorHandler::add('_LB_NOT_GRANTED');
			   		return false;
			   }	
			}		
		}
		return true;
	}

	/**
	 * get password of user
	 *
	 * @param Interger $id
	 * @return string
	 */
	public function getOldPass($id)
	{
		$user = new User();
		$user->id = $id;
		$user->find(true);
		return $user->password;	
	}
	
	/**
	 * update SALT_VALUE
	 *
	 */
	public function updateNewSaltValue()
	{
		$this->salt_value = substr(md5(rand(0, 32000)), 0, 20);
		$this->update();
	}
	
	/**
	 * Login by OneClick
	 *
	 * @param int $rid id of requester
	 * @param int $salt_value salt value
	 * @param int $id id of user
	 * @return boolean true/false true for 
	 */
	public static function validateLoginByOneClick($rid, $salt_value, $id)
	{
		$requester = new User();

		// user is not the current login user
		if ($rid != $id)
		{
			if ($requester->get($rid) && $salt_value == $requester->salt_value)
			{
				// set empty to salt_value of requester
				$requester->salt_value = 'NULL';
				$requester->update();
				
				$user = new User();
				if ($user->get($id) && $user->is_disabled == 0)
				{
					// requester and user are not the same controller type and user is not Support
					if ($user->is_controller != User::QUANLY && $requester->is_controller != $user->is_controller)
					{
						FRM_Session::remove();
						
						// if $user is Admin
						if ($user->is_controller == User::NHANVIEN)
						{
							// save requester data for retransforming later
							FRM_Session::set('retransform_id', $requester->id);
						}				
						
						return true;
					}
				}
			}
		}
		
		return false;
	}

	// check login and use SHA1 to encode password
	function getUserInfo($id)
	{
		$this->joinAdd(new Branch());
		$this->whereAdd("user.id = '" . $id . "'");
		$this->selectAdd();
		$this->selectAdd("user.*");
		$this->selectAdd("branch.name as branch_name");
		$this->is_disabled = 0;
		$this->find();
		if ($this->N)
		{
			$this->fetch();
		}
	}


	/**
	 * Login by OneClick. Automatically login into a specific user by one click
	 * 
	 */
	
	/**
	 * Login by OneClick. Automatically login into a specific user by one click
	 *
	 * @param int $id id of user to who requester want to switch
	 * @param int $site_type APPLICATION_ADMIN, APPLICATION_ADVERTISER or APPLICATION_EDITOR
	 */
	public static function switchByOneClick($id, $site_type = User::APPLICATION_ADMIN)
	{
		// get id of current login user
		$cur_login_user = unserialize(FRM_Session::get('user_serialize'));

		// update new SALT_VALUE
		$cur_login_user->updateNewSaltValue();
		
		// create parameters
		$str_uri = "/login/login/rid/" . $cur_login_user->id . "/sno/" . $cur_login_user->salt_value . "/id/" . $id;
		
		// set flag for this action
		FRM_Session::set('bln_transform', true);
		
		switch ($site_type)
		{
			case User::APPLICATION_ADMIN:
				FRM::redirect(FRM_Config::get('URL', 'ADMIN_BO') . $str_uri);
				break;
			case User::APPLICATION_ADVERTISER:
				FRM::redirect(FRM_Config::get('URL', 'ADVERTISER_BO') . $str_uri);
				break;
			case User::APPLICATION_EDITOR:
				FRM::redirect(FRM_Config::get('URL', 'EDITOR_BO') . $str_uri);
				break;
		}

		FRM::redirect(APPLICATION_URL . '/home/home');
	}
	
	
	
	/**
	 * Get user id by code
	 * @return int $id
	 *
	 * @param string $code
	 */

}
